/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/websocket/chat/{clientId}")
public class WebSocketDemo {

	private static final String GUEST_PREFIX = "Guest";
	private static final AtomicInteger connectionIds = new AtomicInteger(0);
	private static final Set<WebSocketDemo> connections = new CopyOnWriteArraySet<>();

	private final String nickname;
	private Session session;

	public WebSocketDemo() {
		nickname = GUEST_PREFIX  +connectionIds.getAndIncrement();
		System.out.println("每次浏览器的websocket连上服务器端，就会new 出本类的实例： "+nickname);
	}

	@OnOpen
	public void onOpen(@PathParam("clientId") String clientId, Session session) {
		System.out.println("OnOpen! onopen方法会在每次连接上时触发: "+clientId);
		this.session = session;
		connections.add(this);
		String message = String.format("* %s %s", nickname, "has joined.");
		broadcast(message);
	}

	@OnClose
	public void onClose(@PathParam("clientId") String clientId) {
		System.out.println("OnClose! " + clientId);
		connections.remove(this);
		String message = String
				.format("* %s %s", nickname, "has disconnected.");
		broadcast(message);
	}

	@OnMessage
	public void onMessage(@PathParam("clientId") String clientId, String message) {
		// Never trust the client
		System.out.println("OnMessage: " +clientId +": " + message);
		String filteredMessage = String.format("%s: %s", nickname,
				HTMLFilter.filter(message.toString()));
		broadcast(filteredMessage);
	}

	@OnError
	public void onError(Throwable t) throws Throwable {
		System.out.println("OnError: " + t.toString());
//		t.printStackTrace();
	}

	private static void broadcast(String msg) {
		for (WebSocketDemo client : connections) {
			try {
				synchronized (client) {
					client.session.getBasicRemote().sendText(msg);
				}
			} catch (IOException e) {
				System.out
						.println("Chat broadcast Error: Failed to send message to client");
				e.printStackTrace();
				connections.remove(client);
				try {
					client.session.close();
				} catch (IOException e1) {
					// Ignore
				}
				String message = String.format("* %s %s", client.nickname,
						"has been disconnected.");
				broadcast(message);
			}
		}
	}
}
